using System;
using System.Xml;
using Microsoft.Practices.Unity.Configuration;

namespace Common.Unity.Configuration
{
	public class InjectionParameterValueElementResolver
	{
		const string ValueName = "value", DependencyName = "dependency";

		public InjectionParameterValueElement Resolve( string elementName, XmlReader reader )
		{
			switch(elementName)
			{
				case ValueName:
					return Deserialize<InstanceValueElement>( reader );
				case DependencyName:
					return Deserialize<DependencyValueElement>( reader );
				default:
					return Deserialize( reader );
			}
		}

		static InjectionParameterValueElement Deserialize<ResultType>( XmlReader reader ) where ResultType : InjectionParameterValueElement, new()
		{
			ResultType result = new ResultType();
			result.DeserializeElement( reader );
			return result;
		}

		static InjectionParameterValueElement Deserialize( XmlReader reader )
		{
			string elementTypeName = reader.GetAttribute("elementType");
			if ( !string.IsNullOrEmpty( elementTypeName ) )
			{
				Type elementType = Type.GetType( elementTypeName );
				InjectionParameterValueElement result = (InjectionParameterValueElement)Activator.CreateInstance( elementType );
				result.DeserializeElement(reader);
				return result;
			}
			return null;
		}
	}
}